﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;


public class ChapterDownload
{
    private IList<string> ImageLinks;
    private int indexOfList = 0;
    private string userDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    private MangaInfo manga;
    private string mangaFolder = "";
    private string chapterFolder = "";
    public ChapterDownload(IList<string> ImageLinks)
    {
        // TODO: Complete member initialization
        this.ImageLinks = ImageLinks;
    }

    public ChapterDownload(IList<string> ImageLinks, MangaInfo manga, string chapterTitle)
    {
        // TODO: Complete member initialization
        this.ImageLinks = ImageLinks;
        this.manga = manga;
        this.mangaFolder = manga.MangaFolder;
        this.chapterFolder = chapterTitle;
    }


    public void Start()
    {
        string link = "";

        // Check manga folder
        if (Directory.Exists(String.Format("{0}\\{1}", userDesktopPath, mangaFolder)) == false)
        {
            Directory.CreateDirectory(String.Format("{0}\\{1}", userDesktopPath, mangaFolder));
        }

        // Check chapter folder
        if (Directory.Exists(String.Format("{0}\\{1}\\{2}", userDesktopPath, mangaFolder, chapterFolder)) == false)
        {
            Directory.CreateDirectory(String.Format("{0}\\{1}\\{2}", userDesktopPath, mangaFolder, chapterFolder));
        }

        // download images of chapter
        for (int index = 0; index < ImageLinks.Count(); index++)
        {
            link = ImageLinks[index];

            string filePath = String.Format("{0}\\{1}\\{2}\\{3}.jpg", userDesktopPath, mangaFolder, chapterFolder, index.ToString("D3"));

            WebClient webGetImage = new WebClient();

            byte[] result = webGetImage.DownloadData(link);
            using (FileStream fileStream = System.IO.File.Create(filePath, (int)result.Length))
            {
                // Use FileStream object to write to the specified file
                fileStream.Write(result, 0, result.Length);
                fileStream.Flush();
                fileStream.Close();
            }
        }
    }
}


